import React, { useEffect, useState } from 'react';
import { Menu, Layout, Breadcrumb } from 'antd';
import styles from './GoodsLayout.less';
import { connect, history } from 'umi';
import type { ConnectRC } from 'umi';
import type { GoodsInfoModelState } from '@/models/goods';
const { Content, Sider } = Layout;
import { PieChartOutlined } from '@ant-design/icons';
interface GoodsDetailProps {
  info: GoodsInfoModelState['info'];
}
const GoodsLayout: ConnectRC<GoodsDetailProps> = (props) => {
  const { children, match, dispatch, location } = props;
  const [selectedKeys, setSelectedKeys] = useState<string>('goods-detail');
  useEffect(() => {
    const pathname = location.pathname;
    const layoutPathname = match.url;
    const key = pathname.replace(layoutPathname, '').replaceAll('/', '');
    if (!key) {
      history.replace(`/goods/detail/${match.params.id}/${selectedKeys}`);
    } else if (key !== selectedKeys) {
      setSelectedKeys(key);
    }
  }, [location.pathname]);
  useEffect(() => {
    if (match.params?.id && dispatch) {
      dispatch({
        type: 'goods/fetchRoleList',
        payload: { id: match.params.id },
      });
    }
    return () => {
      dispatch({
        type: 'goods/saveGoodsInfoList',
        payload: {},
      });
    };
  }, [match.params.id]);

  const topData = {
    'goods-detail': '商品详情',
  };
  const onSelect = ({ key }: { key: string }) => {
    setSelectedKeys(key);
    history.push(`/goods/detail/${match.params.id}/${key}`);
  };
  return (
    <Layout className={styles.layoutStyle}>
      <Sider width={160} className={styles.siderStyle}>
        <Menu
          mode="inline"
          theme="light"
          onSelect={onSelect}
          selectedKeys={[selectedKeys]}
          className={styles.menuFixStyle}
        >
          <Menu.Item className={styles.menuItem} key="goods-detail" icon={<PieChartOutlined />}>
            商品详情
          </Menu.Item>
        </Menu>
      </Sider>
      <Content className={styles.contentStyle}>
        <Breadcrumb style={{ background: '#f0f2f5', paddingTop: 15, paddingBottom: 5 }}>
          <Breadcrumb.Item>{topData[`${selectedKeys}`]}</Breadcrumb.Item>
        </Breadcrumb>
        {children}
      </Content>
    </Layout>
  );
};

export default connect(({ goods }: { goods: GoodsInfoModelState }) => ({
  info: goods.info,
}))(GoodsLayout);
